<?php

namespace mpend\modules\user\models;

use Yii;
use yii\db\Exception;
use common\models\user\UserSignin;
use common\models\user\UserSigninHistory;
use common\logics\base\SigninCalendarLogic;
use common\helpers\ArrayHelper;

/**
 * 补签模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SigninRepairCalendarForm extends \common\base\Model {

    /**
     * @integer 用户UID
     */
    public $user_id;

    /**
     * @date 补签日期
     */
    public $date;

    /**
     * 签到
     * @return void
     */
    public function repair() {
        $model = UserSignin::findOrCreate(['user_id' => $this->user_id]);

//        $signDatetime = time();
        $signDatetime = strtotime('-1 day');
        //比对最后签到日期与当前签到日期
        if (date('Y-m-d', $model->last_time) === date('Y-m-d', $signDatetime)) {
            return true;
        } elseif (date('Y-m-d', $model->last_time) > date('Y-m-d', $signDatetime)) {
            //最后签到日期超出当前日期抛出签到异常
            return $this->dumpError('非法请求');
        }

        $formatData = SigninCalendarLogic::format($model->last_time, $model->recent, $signDatetime);

        $duration = ArrayHelper::remove($formatData, 'duration');
        $records = ArrayHelper::remove($formatData, 'records');
        $days = $duration + $records;

        $log = $model->currentLog;
        //首次签到&新签到周期
        if ($days === 0 || $days > date('d', $signDatetime)) {
            //增加新记录
            $log = new UserSigninHistory();
            $log->setAttributes([
                'user_id' => $this->user_id,
                'days' => date('t', $signDatetime),
                'sign_days' => 0,
                'first_date' => date('Y-m-d', $signDatetime),
                'history' => 0,
            ]);
            $model->recent = 0;
        } else {
            //周期内签到
            if ($duration > 0) {
                $model->recent = $model->recent << $duration;
                $log->history = $log->history << $duration;
            } else {
                $model->serial ++;
            }
        }
        if ($log === null) {
            return $this->dumpError('日志错误');
        }
        //设置最后签到日期
        $model->last_time = $signDatetime;
        $log->last_date = date('Y-m-d', $signDatetime);
        if (strtotime($log->first_date) > strtotime($log->last_date)) {
            return $this->dumpError('您在未来的某天已经到访过了，这次我们就当不认识吧~');
        }
        //总签到数增加
        $model->amount ++;
        //周期签到天数增加
        $log->sign_days ++;
        $model->recent ++;
        $log->history ++;

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$log->save()) {
                throw new Exception($log->getErrorMsg());
            }
            $model->current_id = $log->id;
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        $this->addReward($model->recent);
        return true;
    }

    /**
     * 签到奖励
     */
    public function addReward($recent) {
        $index = strlen(decbin($recent)) - 1;

        $peroid = floor($index / SigninCalendarLogic::PERIOD_DAYS) + 1;
        $type = 'credit';
        $number = $peroid * 100;
        if (($index + 1) % SigninCalendarLogic::PERIOD_DAYS === 0) {
            $type = 'box';
            $number = $peroid;
        }

        Yii::error([
            'gold' => 0,
            'credit' => 0,
            'type' => $type,
            'number' => intval($number),
        ], __METHOD__);
    }

}
